// 日视图模块
export function initDayView(views, currentDate, invoke) {
  return {
    updateDayView,
    renderDayTodos
  };

  // 更新日视图
  async function updateDayView() {
    document.getElementById('current-day').textContent = 
      `${formatDate(currentDate)} 星期${['日', '一', '二', '三', '四', '五', '六'][currentDate.getDay()]}`;

    try {
      const todos = await invoke('get_todos_for_day', {
        date: formatDate(currentDate),
      });
      renderDayTodos(todos);
    } catch (error) {
      console.error('加载日视图数据失败:', error);
    }
  }

  // 渲染日视图 Todo 列表
  function renderDayTodos(todos) {
    const list = document.getElementById('day-todo-list');
    list.innerHTML = '';

    // 分组：未完成和已完成
    const incompleteTodos = todos.filter(todo => !todo.completed);
    const completedTodos = todos.filter(todo => todo.completed);

    // 创建表格容器
    const createTableSection = (title, todos) => {
      if (todos.length === 0 && title === '未完成') {
        // 只有未完成部分为空时才显示添加框
        const addRow = document.createElement('div');
        addRow.className = 'todo-table-row add-new';
        const addInput = document.createElement('input');
        addInput.type = 'text';
        addInput.placeholder = '添加新事项...';
        addInput.className = 'edit-input';
        addRow.appendChild(addInput);
        list.appendChild(addRow);

        addInput.addEventListener('keypress', async (e) => {
          if (e.key === 'Enter' && addInput.value.trim()) {
            try {
              await invoke('create_todo', {
                todo: {
                  title: addInput.value.trim(),
                  importance: 'C',
                  urgency: 'C',
                  start_time: getDefaultDueTime(),
                  due_time: getDefaultDueTime(),
                  tags: [],
                  project_id: null,
                  markdown_path: ""
                },
              });
              addInput.value = '';
              updateDayView();
            } catch (error) {
              console.error('创建 Todo 失败:', error);
            }
          }
        });
        return;
      }

      if (todos.length === 0) return;

      const sectionTitle = document.createElement('h3');
      sectionTitle.className = 'todo-section-title';
      sectionTitle.textContent = title;
      list.appendChild(sectionTitle);

      // 创建表格
      const table = document.createElement('div');
      table.className = 'todo-table';

      // 表头
      const headerRow = document.createElement('div');
      headerRow.className = 'todo-table-header';
      headerRow.innerHTML = `
        <div class="todo-col-checkbox"></div>
        <div class="todo-col-title">标题</div>
        <div class="todo-col-urgency">紧急</div>
        <div class="todo-col-importance">重要</div>
        <div class="todo-col-start">开始时间</div>
        <div class="todo-col-due">截止时间</div>
        <div class="todo-col-actions">操作</div>
      `;
      table.appendChild(headerRow);

      // 添加排序事件
      const sortableColumns = ['title', 'urgency', 'importance', 'start_time', 'due_time'];
      sortableColumns.forEach(col => {
        const header = headerRow.querySelector(`.todo-col-${col.replace('_', '-')}`);
        if (header) {
          header.addEventListener('click', () => {
            todos.sort((a, b) => {
              if (col === 'urgency' || col === 'importance') {
                return a[col].localeCompare(b[col]);
              } else if (col === 'start_time' || col === 'due_time') {
                return new Date(a[col] || 0) - new Date(b[col] || 0);
              } else {
                return a[col].localeCompare(b[col]);
              }
            });
            table.innerHTML = '';
            table.appendChild(headerRow);
            renderTableRows(table, todos);
          });
          header.classList.add('sortable');
        }
      });

      // 渲染表格行
      renderTableRows(table, todos);
      list.appendChild(table);
    };

    // 渲染表格行
    const renderTableRows = (table, todos) => {
      todos.forEach(todo => {
        const row = document.createElement('div');
        row.className = `todo-table-row importance-${todo.importance.toLowerCase()}`;
        if (todo.completed) {
          row.classList.add('completed');
        }

        // 复选框
        const checkboxCell = document.createElement('div');
        checkboxCell.className = 'todo-col-checkbox';
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.checked = todo.completed;
        checkbox.addEventListener('change', () => toggleTodoCompletion(todo));
        checkboxCell.appendChild(checkbox);
        row.appendChild(checkboxCell);

        // 标题（可编辑）
        const titleCell = document.createElement('div');
        titleCell.className = 'todo-col-title';
        const titleSpan = document.createElement('span');
        titleSpan.textContent = todo.title;
        titleCell.appendChild(titleSpan);
        row.appendChild(titleCell);

        // 紧急程度
        const urgencyCell = document.createElement('div');
        urgencyCell.className = 'todo-col-urgency urgency-' + todo.urgency.toLowerCase();
        urgencyCell.textContent = todo.urgency;
        row.appendChild(urgencyCell);

        // 重要程度
        const importanceCell = document.createElement('div');
        importanceCell.className = 'todo-col-importance importance-' + todo.importance.toLowerCase();
        importanceCell.textContent = todo.importance;
        row.appendChild(importanceCell);

        // 开始时间
        const startCell = document.createElement('div');
        startCell.className = 'todo-col-start';
        startCell.textContent = todo.start_time ? formatTime(new Date(todo.start_time)) : '-';
        row.appendChild(startCell);

        // 截止时间
        const dueCell = document.createElement('div');
        dueCell.className = 'todo-col-due';
        dueCell.textContent = todo.due_time ? formatTime(new Date(todo.due_time)) : '-';
        row.appendChild(dueCell);

        // 操作按钮
        const actionsCell = document.createElement('div');
        actionsCell.className = 'todo-col-actions';
        const editBtn = document.createElement('button');
        editBtn.className = 'todo-edit-btn';
        editBtn.innerHTML = '⚙️';
        editBtn.addEventListener('click', () => showTodoModal(todo));
        actionsCell.appendChild(editBtn);
        row.appendChild(actionsCell);

        // 双击编辑标题
        titleCell.addEventListener('dblclick', () => {
          const input = document.createElement('input');
          input.type = 'text';
          input.value = todo.title;
          titleCell.innerHTML = '';
          titleCell.appendChild(input);
          input.focus();

          input.addEventListener('blur', async () => {
            if (input.value.trim() && input.value !== todo.title) {
              try {
                const updatedTodo = {
                  ...todo,
                  title: input.value.trim(),
                  start_time: todo.start_time || "",
                  due_time: todo.due_time || "",
                  project_id: todo.project_id || 0,
                  tags: todo.tags || [],
                  markdown_path: todo.markdown_path || ""
                };
                await invoke('update_todo', {
                  id: todo.id,
                  data: updatedTodo
                });
                updateDayView();
              } catch (error) {
                console.error('更新 Todo 失败:', error);
              }
            } else {
              titleCell.innerHTML = '';
              titleCell.textContent = todo.title;
            }
          });

          input.addEventListener('keypress', async (e) => {
            if (e.key === 'Enter') {
              input.blur();
            }
          });
        });

        table.appendChild(row);
      });
    };

    // 计算默认截止时间
    const getDefaultDueTime = () => {
      const now = new Date();
      const today6pm = new Date();
      today6pm.setHours(18, 0, 0, 0);

      if (now > today6pm) {
        const twoHoursLater = new Date(now.getTime() + 2 * 60 * 60 * 1000);
        return formatDate(currentDate) + 'T' + twoHoursLater.toTimeString().substr(0, 5);
      } else {
        return formatDate(currentDate) + 'T18:00';
      }
    };

    // 渲染未完成和已完成部分
    createTableSection('未完成', incompleteTodos);
    createTableSection('已完成', completedTodos);
  }

  // TODO: 需要从utils导入这些工具函数
  function formatDate(date) {
    return date.toISOString().split('T')[0];
  }

  function formatTime(date) {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
    });
  }
}